﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WF.Common;

namespace WF.Web.Pages.Workflow.KQ
{
    public partial class ComApproval : BasePageWorkflow
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            #region 页面加载（不需更改）
            //指定流程类型
            //this.SetApplyType();            

            //取得流程步骤的SN
            this.sn = Request.QueryString["SN"];
            //CentaUtil.CheckParam(this.sn, "流程SN");

            this.ManagedUser = Request.QueryString["ManagedUser"];
            this.SharedUser = Request.QueryString["SharedUser"];

            //取得K2连接
            this.oK2Connection = WorkFlowHelper.GetK2Connection();
            this.oK2Connection.ImpersonateUser(userProfile.LoginName);

            if (!WorkFlowHelper.CheckWorkListItem(this.oK2Connection, this.sn, this.ManagedUser, this.SharedUser))
            {
                this.FormView1.Visible = false;
                this.btnSubmit.Enabled = false;
                string errMsg = "打开待办事项失败!\r可能原因：1）你无权限打开此待办事项；2）此待办事项已经被他人打开处理。";
                //WorkFlowHelper.ShowWarningMessage(Page, errMsg);
                this.ShowMessage(errMsg, true);
                return;
            }

            //获取流程待办事项，并关闭K2连接
            SourceCode.Workflow.Client.WorklistItem worklistItem = WorkFlowHelper.GetWorkListItemBySN(this.oK2Connection, this.sn, this.ManagedUser, this.SharedUser);

            //为WorkFlow的各个公用变量赋值
            //this.ApplyID = WorkFlowHelper.GetInstanceDataFields(worklistItem, "ApplyID", false);
            this.bizDataID = WorkFlowHelper.GetInstanceDataFields(worklistItem, "FlowID", false);
            this.txtIsKQAuditDeptManager.Text = WorkFlowHelper.GetInstanceDataFields(worklistItem, "IsKQAuditDeptManager", false);
            this.txtBillTypeSubCode.Text = WorkFlowHelper.GetInstanceDataFields(worklistItem, "BillTypeSubCode", false);
            this.CurrentActivityName = WorkFlowHelper.GetCurrentActivityName(worklistItem);
            this.CurrentActivityDisplayName = WorkFlowHelper.GetCurrentActivityDisplayName(worklistItem);
            this.lblCurrentActivityName.Text = this.CurrentActivityDisplayName;

            if (!this.IsPostBack)
            {
                //加载流程表单信息(用formview绑定)
                this.LoadFormViewData();

                //加载历史审批记录            
                WorkFlowHelper.BindApprovalAuditHistory(worklistItem, this.dataListView);

                //绑定审核操作选择项
                this.BindApprovalResult(rblComAuditResult);

                //绑定审批提交按钮的客户端校验事件
                WorkFlowHelper.SetSubmitClientScript(this.rblComAuditResult, this.btnSubmit);
            }

            this.oK2Connection.Close();

            ((HyperLink)FormView1.FindControl("lnkView")).NavigateUrl = "Attachment.aspx?KQAPPLYID=" + ((HiddenField)FormView1.FindControl("txtFlowID")).Value;
            ((HyperLink)FormView1.FindControl("lnkView")).Attributes.Add("onclick", "return ShowDialog(this, 650, 450, '');");
            #endregion
        }

        #region 私有方法（需要实现）
        /// <summary>
        /// 加载流程表单信息
        /// </summary>
        private void LoadFormViewData()
        {
            //this.ObjectDataSource1.SelectParameters.Add("ID", this.bizDataID); 
            this.ObjectDataSource1.SelectParameters["ID"].DefaultValue = this.bizDataID;
            //this.FormView1.DataSource = this.ObjectDataSource1;
            this.FormView1.DataBind();

            //如果页面控件有特别的控制加在下面
            if (this.CurrentActivityDisplayName == "申请人修改")
            {
                return;
            }
            else if (this.CurrentActivityDisplayName == "人事专员审核")
            {
                CentaUtil.SetControlReadOnly(this.FormView1, true);
                //((DropDownList)this.FormView1.Row.FindControl("ddlFlagMin")).Enabled = true;
            }
            else if ((this.txtBillTypeSubCode.Text != "0" & (this.txtIsKQAuditDeptManager.Text.ToString() == "1" || this.CurrentActivityDisplayName == "上级审批" || this.CurrentActivityDisplayName == "二级上级审批")))
            {
                CentaUtil.SetControlReadOnly(this.FormView1, true);
                this.trHrAuditor.Visible = true;
                this.rblHrAuditor.Enabled = true;
            }
            else
            {
                CentaUtil.SetControlReadOnly(this.FormView1, true);
                //((Button)this.FormView1.Row.FindControl("btnSelectDept")).Visible = false;
                //((TextBox)this.FormView1.Row.FindControl("txtDateBegin")).CssClass = "inputs";
                //((TextBox)this.FormView1.Row.FindControl("txtDateBegin")).Attributes["onfocus"] = "";
            }
        }
        /// <summary>
        /// 设置审批选项
        /// </summary>
        /// <param name="radioButtonList"></param>
        /// <param name="p"></param>
        /// <param name="p_2"></param>
        private void BindApprovalResult(RadioButtonList radioButtonList)
        {
            radioButtonList.Items.Clear();
            switch (this.CurrentActivityDisplayName)
            {
                case "申请人修改":
                    radioButtonList.Items.Add(new ListItem("修改完成", "1"));
                    radioButtonList.SelectedValue = "1";
                    break;
                default:
                    radioButtonList.Items.Add(new ListItem("通过", "1"));
                    //radioButtonList.Items.Add(new ListItem("驳回修改", "2"));
                    radioButtonList.Items.Add(new ListItem("拒绝", "0"));
                    radioButtonList.SelectedValue = "1";
                    break;
            }

            #region 如果没有不显示(公用不需改)
            if (rblComAuditResult.Items.Count == 0)
            {
                this.trComAuditResult.Visible = false;
            }
            #endregion
        }
        #endregion

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                using (System.Transactions.TransactionScope t = new System.Transactions.TransactionScope())
                {
                    //如果是修改步骤 -> 保存数据
                    if (this.CurrentActivityName == "申请人修改" || this.CurrentActivityDisplayName == "人事专员审核")
                    {
                        //保存数据                                                
                        this.FormView1.UpdateItem(true);
                    }

                    #region 连接K2（公用不需改)
                    this.oK2Connection = WorkFlowHelper.GetK2Connection();
                    this.oK2Connection.ImpersonateUser(userProfile.LoginName);
                    #endregion

                    if (this.txtBillTypeSubCode.Text != "0" & (txtIsKQAuditDeptManager.Text.ToString() == "1" || this.CurrentActivityDisplayName == "上级审批" || this.CurrentActivityDisplayName == "二级上级审批") & this.rblHrAuditor.SelectedValue.ToString() == "")
                    {
                        this.ShowMessage("请选择所属区域人事审核", false, false);
                        return;
                    }
                    else if (this.txtBillTypeSubCode.Text != "0" & (txtIsKQAuditDeptManager.Text.ToString() == "1" || this.CurrentActivityDisplayName == "上级审批" || this.CurrentActivityDisplayName == "二级上级审批") & this.rblHrAuditor.SelectedValue.ToString() != "")
                    {
                        WorkFlowHelper.SetInstanceDataFields(this.oK2Connection, this.sn, "HRAuditorDomainAccount", this.rblHrAuditor.SelectedValue, false, this.ManagedUser, this.SharedUser);
                    }

                    //如果需要改流程的datafield->更新
                    if (this.CurrentActivityName == "申请人修改")
                    {
                        //设置流程的folio     
                        //string curParentID = ((TextBox)this.FormView1.Row.FindControl("txtCurParentID")).Text;
                        //string curParentFullName = ((TextBox)this.FormView1.Row.FindControl("txtCurParentFullNameHide")).Text;
                        // string deptName = ((TextBox)this.FormView1.Row.FindControl("txtDeptName")).Text;
                        //string folio = "[" + userProfile.DeptName + " " + userProfile.Empname + "]提交的[" + WF.Common.WorkFlowHelper.WF_APPLY_TYPE_DEPT_ADD + "]（" + curParentFullName + "/" + deptName + "）";
                        //WorkFlowHelper.SetInstanceFolio(this.oK2Connection, this.sn, folio, this.ManagedUser, this.SharedUser);
                        //设置需要更新的datafield                        
                        // WorkFlowHelper.SetInstanceDataFields(this.oK2Connection, this.sn, "BizDeptID", curParentID, false, this.ManagedUser, this.SharedUser);
                        // WorkFlowHelper.SetInstanceDataFields(this.oK2Connection, this.sn, "BizDeptName", deptName, false, this.ManagedUser, this.SharedUser);
                    }

                    #region 记录审批结果，提交审批，并关闭K2连接，关掉窗口（公用不需改）
                    //设置审批结果,并完成审批

                    if (this.rblComAuditResult.Items.Count > 0)
                    {
                        auditResultValue = this.rblComAuditResult.SelectedValue;
                        auditResultText = this.rblComAuditResult.SelectedItem.Text;
                    }
                    WorkFlowHelper.SetApprovalResult(this.oK2Connection,
                        userProfile, sn, auditResultValue, auditResultText,
                        txtComAuditComment.Text.Trim(),
                        this.CurrentActivityDisplayName,
                        this.ManagedUser,
                        this.SharedUser);

                    //关闭当前审批窗口 
                    this.oK2Connection.Close();

                    t.Complete();

                    //关闭窗口返回true this.WindowClose(true);                    
                    this.ShowMessage("操作成功", true, true);
                    #endregion
                }
            }
            catch (Exception ex)
            {
                this.Master.HandleException(ex, true);
            }
            finally
            {
                try
                {
                    oK2Connection.Close();
                }
                catch { }
            }
        }
    }
}